import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../../class/dialog/effect_view.dart';
import '../../class/eq/eq_group.dart';
import '../../class/eq/eq_swipe.dart';
import '../../commont/base_controller.dart';
import '../../model/model.dart';
import '../../model/model_default.dart';
import '../../notify/globalState.dart';
import '../../tool/assets.dart';
import '../cross/ch_select.dart';
import 'eq_setting.dart';

class EqController extends BaseController {
  EqController({super.key});
  @override
  State<EqController> createState() => kstate = _EqControllerState();
}

class _EqControllerState extends BaseControllerState<EqController> {
  late final List<List<GroupModel>> _list;
  int _current_page = 0;
  int _select_effect = -1;
  List<Map<String, List<SignModel>>> get _sign_list {
    return [
      {assets.ONE: current_ch.sign_list.sublist(0, 8)},
      {assets.TWO: current_ch.sign_list.sublist(8, 16)},
      {assets.THREE: current_ch.sign_list.sublist(16, 24)},
      {assets.FOUR: current_ch.sign_list.sublist(24, 31)}
    ];
  }

  bool get enable {
    return globalModel.enable && _list[0][0].select == false;
  }

  @override
  void initState() {
    super.initState();
    List<GroupModel> other = ['EQ Defeat', 'Audio Presets', 'Reset EQ'].map(($0) {
      return GroupModel(name: $0);
    }).toList();
    _list = [other, group_list];
  }

  void _onclickGroup(GroupModel group) {
    switch (group.name) {
      case 'EQ Defeat':
        group.select = !group.select;
        for (var sub_list in _list) {
          for (var $0 in sub_list) {
            $0.enable = $0.name == group.name || group.select == false;
          }
        }
        setState(() {});
      case 'Audio Presets':
        Effect effect = Effect(select_effect: _select_effect);
        effect.show(context);
        effect.onClick = (index, data) {
          _select_effect = index;
          for (var ch in globalModel.ch_list) {
            for (var i = 0; i < ch.sign_list.length; i++) {
              ch.sign_list[i].gain = data[i].toDouble();
              ch.sign_list[i].Q = 7.2;
              ch.sign_list[i].freq = sign_freq_list[i];
            }
          }
          _send_data('EQ_ALL', null);
          globalState.state = NotifyData(key: '全部刷新');
        };
      case 'Reset EQ':
        break;
      default:
        onclickGroup(group);
    }
  }

  void _onLongPressGroup(GroupModel group) {
    switch (group.name) {
      case 'EQ Defeat':
        break;
      case 'Audio Presets':
        break;
      case 'Reset EQ':
        _select_effect = -1;
        for (var ch in globalModel.ch_list) {
          for (var i = 0; i < ch.sign_list.length; i++) {
            ch.sign_list[i].gain = 0;
            ch.sign_list[i].Q = 7.2;
            ch.sign_list[i].freq = sign_freq_list[i];
          }
        }

        globalState.state = NotifyData(key: '全部刷新');
        _send_data('EQ_RESET', null);
      default:
        onLongPressGroup(group);
    }
  }

  ///当sign模块改变值时，除了取消其他sign的选中状态，还要进行group的 统一
  void onChangeForSign(SignModel sign, String tag) {
    _select_effect = -1;
    for (var $0 in current_ch.sign_list) {
      $0.select = sign.name == $0.name;
    }
    unitChannel(current_ch);
    if (tag != '') {
      _send_data('EQ', sign);
    }
  }

  @override
  void realod() {
    super.realod();
    for (var sub_list in _list) {
      for (var $0 in sub_list) {
        if (globalModel.enable == false) {
          $0.enable = false;
        } else {
          $0.enable = $0.name == _list[0][0].name || _list[0][0].select == false;
        }
      }
    }
    setState(() {});
  }

  @override
  void copy(ChannelModel model, ChannelModel from) {
    for (var i = 0; i < from.sign_list.length; i++) {
      model.sign_list[i].Q = from.sign_list[i].Q;
      model.sign_list[i].freq = from.sign_list[i].freq;
      model.sign_list[i].gain = from.sign_list[i].gain;
      model.sign_list[i].select = from.sign_list[i].select;
    }
  }

  @override
  Widget buildContent(BuildContext context) {
    return Column(children: [
      ChSelect(
          ch_list: globalModel.ch_list,
          enable: enable,
          onClick: (p0) {
            setState(() {
              unitChannel(p0);
              select_list = globalModel.ch_list.map(($0) => $0.select).toList();
            });
          }),
      const SizedBox(height: 5),
      EqSwipe(
        sign_list: _sign_list,
        enable: enable,
        onChange: onChangeForSign,
        onChangeForSend: (p0) {
          _send_data('EQ', p0);
        },
        onSwipe: (p0) {
          setState(() {
            _current_page = p0;
          });
        },
      ),
      EqSetting(
        sign_list: _sign_list[_current_page].values.first,
        enable: enable,
        onChange: onChangeForSign,
        onChangeForSend: (p0) {
          _send_data('EQ', p0);
        },
      ),
      EqSetting(
        up: false,
        sign_list: _sign_list[_current_page].values.first,
        enable: enable,
        onChange: onChangeForSign,
        onChangeForSend: (p0) {
          _send_data('EQ', p0);
        },
      ),
      const SizedBox(height: 5),
      EqGroup(list: _list, onClick: _onclickGroup, onLongPress: _onLongPressGroup),
    ]);
  }
}

///发送数据
extension EqControllerExtension on _EqControllerState {
  void _send_data(String tag, SignModel? sign) {
    if ((tag != 'EQ' && tag != 'EQ_ALL' && tag != 'EQ_RESET')) return;
    if (tag == 'EQ_ALL') {
      ///由于可能蓝牙队列里，等待传输数据很多 ，队列可能还有很多任务没完成，所以每次强制清空下队列，以便最快生效

      List<ChannelModel> list = [];

      ///1，全部数组对半处理，同时发送蓝牙数据时候，采用联调命令 ，让发送数据减半
      for (var i = 0; i < globalModel.ch_list.length / 2; i++) {
        ChannelModel sub_ch = globalModel.ch_list[i * 2];
        list.add(sub_ch);
      }

      ///2，再排序，把当前选中的放前面，优先生效
      List<ChannelModel> select_list = list.where(($0) => $0.select || globalModel.ch_list[$0.num].select).toList();
      List<ChannelModel> unselect_list = list.where(($0) => !$0.select && !globalModel.ch_list[$0.num].select).toList();
      list = [...select_list, ...unselect_list];

      ///3，处理数据，准备发送

      List<int> num_list = [];
      List<SignModel> sign_list = [];
      for (var sub_ch in list) {
        for (var sign in sub_ch.sign_list) {
          num_list.add(sub_ch.num);
          sign_list.add(sign);
        }
      }

      _send_qe_all('EQ', 0, num_list, sign_list);

      return;
    } else if (tag == 'EQ_RESET') {
      globalState.state = NotifyData(key: tag, body: current_ch);
      EasyLoading.showSuccess('Successfully!');
      return;
    } else {
      String message = '${current_ch.num}';
      for (var group in select_group_list) {
        if (group.contain(current_ch)) {
          ChannelModel other_ch = group.ch1!.num == current_ch.num ? group.ch2! : group.ch1!;
          message += '&${other_ch.num}';
        }
      }

      globalState.state = NotifyData(key: tag, message: message, body: sign);
    }
  }

  void _send_qe_all(String tag, int index, List<int> num_list, List<SignModel> sign_list) {
    if (index == 0) {
      ///这里增加个吐司，模拟所有数据传完。
      EasyLoading.show(status: 'Please waitting...', dismissOnTap: false);
    }
    if (index < 124) {
      int num = num_list[index];
      SignModel sign = sign_list[index];
      globalState.state = NotifyData(key: tag, message: '${num}&${num + 1}', body: sign);
      Future.delayed(const Duration(milliseconds: 10), () {
        _send_qe_all(tag, index + 1, num_list, sign_list);
      });
    } else {
      Future.delayed(const Duration(seconds: 2), () {
        EasyLoading.showSuccess('Successfully!', duration: const Duration(milliseconds: 1000));
      });
    }
  }
}
